const fileCache = require('think-cache-file');
const nunjucks = require('think-view-nunjucks');
const fileSession = require('think-session-file');
const mysql = require('think-model-mysql');
const { Console, File, DateFile } = require('think-logger3');
const path = require('path');
const isDev = think.env === 'development';
/**
 * cache adapter config
 * @type {Object}
 */
exports.cache = {
	type: 'file',
	common: {
		timeout: 24 * 60 * 60 * 1000 // millisecond
	},
	file: {
		handle: fileCache,
		cachePath: path.join(think.ROOT_PATH, 'runtime/cache'), // absoulte path is necessarily required
		pathDepth: 1,
		gcInterval: 24 * 60 * 60 * 1000 // gc interval
	}
};
/**
 * model adapter config
 * @type {Object}
 */
exports.model = {
	type: 'mysql',
	common: {
		logConnect: isDev,
		logSql: isDev,
		logger: msg => think.logger.info(msg)
	},
	mysql: {
		handle: mysql,
		database: 'nodetbk',
		prefix: '',
		encoding: 'utf8mb4',
//		host: '',
		host: '127.0.0.1',
		port: '3306',
		user: 'root',
		password: 'root',
		dateStrings: true
	}
};
/**
 * session adapter config
 * @type {Object}
 */
exports.session = {
	type: 'file',
	common: {
		cookie: {
			name: 'thinkjs'
			// keys: ['werwer', 'werwer'],
			// signed: true
		}
	},
	file: {
		handle: fileSession,
		sessionPath: path.join(think.ROOT_PATH, 'runtime/session')
	}
};
/**
 * view adapter config
 * @type {Object}
 */
exports.view = {
	type: 'nunjucks',
	common: {
		viewPath: path.join(think.ROOT_PATH, 'view'),
		sep: '_',
		extname: '.html'
	},
	nunjucks: {
		handle: nunjucks,
		beforeRender: (env, nunjucks, config) => {
			env.addExtension('model', new model(), true);
			env.addExtension('appModel', new appModel(), true);
			
			env.addFilter('stringify', function(obj) {
				return JSON.stringify(obj);
			});
			
			env.addFilter('split', (str, chr) => {
				return str.split(chr);
			});
			env.addFilter('date', (str, chr) => {
				return think.datetime(str).slice(0, 10);
			});
			env.addFilter('datetime', (str, chr) => {
				return think.datetime(str);
			});
			env.addFilter('getpage', (num, cur) => {
				let arr = [];
				for(let i = 1; i <= num; i++) {
					arr.push(i);
				}
				let begin =0;
				if(cur <= num-4 && cur >=  4) {
					begin = cur-2;
				}
				
				if(cur>num-4) {
					begin = num -5;
				}
				if(num < 5){
					begin = 0
				}
				
				return arr.slice(begin, begin+5);
				
			});
			env.addFilter('utf8', (str, chr) => {
				return think.utf8(str);
			});
		}
	}
};
/**
 * logger adapter config
 * @type {Object}
 */
exports.logger = {
	type: isDev ? 'console' : 'dateFile',
	console: {
		handle: Console
	},
	file: {
		handle: File,
		backups: 10, // max chunk number
		absolute: true,
		maxLogSize: 50 * 1024, // 50M
		filename: path.join(think.ROOT_PATH, 'logs/app.log')
	},
	dateFile: {
		handle: DateFile,
		level: 'ALL',
		absolute: true,
		pattern: '-yyyy-MM-dd',
		alwaysIncludePattern: true,
		filename: path.join(think.ROOT_PATH, 'logs/app.log')
	}
};